import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';

import { getTopBannerAction } from '../../store/actionCreators';

import { BannerWrapper, BannerLeft, BannerRight, BannerControl } from './style';
import { Carousel } from 'antd';

export default memo(function JPTtopBanners() {
  // render hooks
  const dispath = useDispatch();

  const { topBanners } = useSelector(
    (state) => ({
      topBanners: state.getIn(['recommend', 'topBanners'])
    }),
    shallowEqual
  );

  // 其他hooks
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    if (!topBanners || topBanners.length <= 0) {
      dispath(getTopBannerAction);
    }
  }, [topBanners, dispath]);

  const bannerRef = useRef();

  const bannerChange = useCallback((from, to) => {
    setCurrentIndex(to);
  }, []);

  const bigImageBg =
    topBanners &&
    topBanners[currentIndex] &&
    topBanners[currentIndex].imageUrl + '?imageView&blur=40x20';

  return (
    <BannerWrapper bgImage={bigImageBg}>
      <div className="wrap-v2 banner">
        <BannerLeft>
          <Carousel
            effect="fade"
            ref={bannerRef}
            autoplay
            beforeChange={bannerChange}
          >
            {topBanners.map((item) => {
              return (
                <div className="banner-item" key={item.imageUrl}>
                  <img
                    className="image"
                    src={item.imageUrl}
                    alt={item.typeTitle}
                  />
                </div>
              );
            })}
          </Carousel>
        </BannerLeft>
        <BannerRight />
        <BannerControl>
          <button
            className="btn left"
            onClick={(e) => bannerRef.current.prev()}
          ></button>
          <button
            className="btn right"
            onClick={(e) => bannerRef.current.next()}
          ></button>
        </BannerControl>
      </div>
    </BannerWrapper>
  );
});
